package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.LoginFormDTO;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.User;
import com.hmdp.mapper.UserMapper;
import com.hmdp.service.IUserService;
import com.hmdp.utils.LoginEnum;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.RegexUtils;
import com.hmdp.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.connection.BitFieldSubCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.nio.file.CopyOption;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Result sendCode(String phone, HttpSession session) {

        if(RegexUtils.isPhoneInvalid(phone)) {
            return Result.fail("手机号格式错误");
        }

        String code = RandomUtil.randomNumbers(6);

        stringRedisTemplate.opsForValue().set(LoginEnum.LOGIN_CODE.getName() + phone, code);
        stringRedisTemplate.expire(LoginEnum.LOGIN_CODE.getName() + phone, 2, TimeUnit.MINUTES);
        log.info("发送短信验证码成功，验证码：{}", code);

        return Result.ok();
    }

    @Override
    public Result checkLogin(LoginFormDTO loginForm) {

        if(RegexUtils.isPhoneInvalid(loginForm.getPhone())) {
            return Result.fail("手机号格式错误");
        }

        String s = stringRedisTemplate.opsForValue().get(LoginEnum.LOGIN_CODE.getName() + loginForm.getPhone());

        if (StrUtil.isBlank(s) || !loginForm.getCode().equals(s)) {
            return Result.fail("验证码错误");
        }

        User user = query().eq("phone", loginForm.getPhone()).one();

        if (user == null) {
            user = createUserWithPhone(loginForm.getPhone());
        }
        String token = UUID.randomUUID().toString();
        UserDTO userDTO = BeanUtil.copyProperties(user, UserDTO.class);
        // Map<String, Object> userMap = BeanUtil.beanToMap(userDTO);
        Map<String, Object> userMap = BeanUtil.beanToMap(userDTO, new HashMap<>(),
        // 把map的value值转换成String，确保能成功放入stringRedis中
        CopyOptions.create()
                .setFieldValueEditor((fieldName, fieldValue) -> (
                    fieldValue.toString()
                )));

        stringRedisTemplate.opsForHash().putAll(LoginEnum.LOGIN_KEY.getName() + token, userMap);
        stringRedisTemplate.expire(LoginEnum.LOGIN_KEY.getName() + token, 30, TimeUnit.MINUTES);

        return Result.ok(token);
    }

    @Override
    public Result sign() {
        String userId = UserHolder.getUser().getId().toString();
        LocalDateTime now = LocalDateTime.now();
        String format = now.format(DateTimeFormatter.ofPattern(":yyyyMM"));
        String key = RedisConstants.USER_SIGN_KEY + userId + format;
        // 今日（从0开始，0是1号
        int dayOfMonth = now.getDayOfMonth() - 1;
        // 今日位设为1
        stringRedisTemplate.opsForValue().setBit(key, dayOfMonth, true);
        return Result.ok();
    }

    @Override
    public Result signCount() {

        String userId = UserHolder.getUser().getId().toString();
        LocalDateTime now = LocalDateTime.now();
        String format = now.format(DateTimeFormatter.ofPattern(":yyyyMM"));
        int dayOfMonth = now.getDayOfMonth();
        String key = RedisConstants.USER_SIGN_KEY + userId + format;
        List<Long> signData = stringRedisTemplate
                .opsForValue()
                // 从bitmap的key中获取无符号dayOfMonth位，从0开始获取（获取第一天到今天的签到记录
                .bitField(key, BitFieldSubCommands.create().get(BitFieldSubCommands.BitFieldType.unsigned(dayOfMonth)).valueAt(0));
        if (signData == null || signData.isEmpty()) {
            return Result.ok(0);
        }
        // 从BitMap中拿到的值是十进制的
        Long total = signData.get(0);
        if (total == null || total == 0) {
            return Result.ok(0);
        }

        int count = 0;
        while (true) {
            // 不断获取最低位，是1则count++，以此得到连续签到天数
            if ((total & 1) == 1) {
                count++;
                total >>>= 1;
            } else {
                break;
            }
        }

        return Result.ok(count);
    }

    private User createUserWithPhone(String phone) {
        User user = new User();
        user.setPhone(phone);
        user.setNickName(RandomUtil.randomString(8));
        save(user);
        return user;
    }
}
